/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package hhf.logger;

import java.lang.reflect.Method;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import javax.annotation.Resource;
import javax.ejb.EJBContext;
import javax.ejb.Stateless;
import javax.ejb.LocalBean;
import javax.interceptor.ExcludeDefaultInterceptors;
import org.slf4j.MDC;

/**
 *
 * @author François
 */
@Stateless
@LocalBean
@ExcludeDefaultInterceptors
public class MDCInitializer {

	@Resource
	private EJBContext ejbc;
//	@Resource(lookup = "java:module/ModuleName")
//	private String moduleName;
	@Resource(lookup = "java:app/AppName")
	private String appName;

	public String computeMDC(Class target, Method method) {
		return computeMDC(target.getName() + "." + method.getName());
	}

	public String computeMDC(String actionName) {
		String userid = MDC.get("userid");
		String deep = MDC.get("deep");
		if (deep == null) {
			deep = "";
			MDC.put("deep", deep);
		} else {
			String moredeep = deep.replaceAll("¯", " ") + "|¯";
			MDC.put("deep", moredeep);
		}
		if (userid == null) {
			userid = ejbc.getCallerPrincipal().getName();
			MDC.put("app", appName);
			MDC.put("userid", userid);
			MDC.put("action", actionName);
			DateFormat df = new SimpleDateFormat("HHmmssSSS");
			MDC.put("actionid", df.format(new Date()));
		}
		return deep;
	}
}
